package com.eduadmin.controller;

import com.eduadmin.entity.*;
import com.eduadmin.service.*;
import com.eduadmin.utils.CpachaUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SystemController {
    //构造函数自动装配
    private final IAdminLoginService adminLoginService;
    private final IStudentService studentService;
    private final ITeamService teamService;
    private final ICourseService courseService;
    private final ITeacherService teacherService;
    private final IGradeService gradeService;
    private final IStatisticsService statisticsService;
    private final ISemesterService semesterService;
    private final IExamService examService;
    private final ICategoryService categoryService;
    private final IStatisticsFinishedService statisticsFinishedService;
    private final ITeachInfoService teachInfoService;
    private final IScoreService scoreService;

    @Autowired
    public SystemController(ICourseService courseService,
                            ITeamService teamService,
                            IAdminLoginService adminLoginService,
                            IStudentService studentService,
                            ITeacherService teacherService,
                            IGradeService gradeService,
                            IStatisticsService statisticsService,
                            ISemesterService semesterService,
                            IExamService examService,
                            ICategoryService categoryService,
                            IStatisticsFinishedService statisticsFinishedService,
                            ITeachInfoService teachInfoService,
                            IScoreService scoreService) {
        this.adminLoginService = adminLoginService;
        this.teamService = teamService;
        this.courseService = courseService;
        this.studentService = studentService;
        this.teacherService = teacherService;
        this.gradeService = gradeService;
        this.statisticsService = statisticsService;
        this.semesterService = semesterService;
        this.examService = examService;
        this.categoryService = categoryService;
        this.statisticsFinishedService = statisticsFinishedService;
        this.teachInfoService = teachInfoService;
        this.scoreService = scoreService;
    }

    @RequestMapping(value = "index")
    public String index() {
        return "index";
    }

    @RequestMapping(value = "adminindex")
    public String adminindex() {
        return "admin/adminindex";
    }

    @RequestMapping(value = "adminwelcome")
    public String adminwelcome() {
        return "admin/welcome";
    }

    @RequestMapping(value = "studentindex")
    public String studentindex() {
        return "student/studentindex";
    }

    @RequestMapping(value = "studentwelcome")
    public String studentwelcome() {
        return "student/welcome";
    }

    @RequestMapping(value = "teacherindex")
    public String teacherindex() {
        return "teacher/teacherindex";
    }

    @RequestMapping(value = "teacherwelcome")
    public String teacherwelcome() {
        return "teacher/welcome";
    }

    @RequestMapping(value = "basedatainput")
    public String gradeinfo() {
        return "admin/basedatainput";
    }

    /*zlc 添加路由*/
    //管理员：管理基础数据
    @RequestMapping(value = "managebasedata")
    public String managebasedata() {
        return "admin/managebasedata";
    }

    //管理员：统计报表
    @RequestMapping(value = "statisticsdata")
    public String statisticsdata() {
        return "admin/statisticsdata";
    }

    //管理员：查询成绩
    @RequestMapping(value = "queryscore")
    public String queryscore() {
        return "admin/queryscore";
    }

    // 管理员：查询统计报表
    @RequestMapping(value = "querystatistics")
    public String querystatistics() {
        return "admin/querystatistics";
    }

    // 教师：登录查询学生成绩
    @RequestMapping(value = "queryteacherscore")
    public String queryteacherscore() {
        return "teacher/queryteacherscore";
    }

    // 教师：登录查询统计报表
    @RequestMapping(value = "queryteacherstatistics")
    public String queryteacherstatistics() {
        return "teacher/queryteacherstatistics";
    }

    // 学生：登录查询学生成绩
    @RequestMapping(value = "querystudentscore")
    public String querystudentscore() {
        return "student/querystudentscore";
    }

    //图表1：成绩分布
    @RequestMapping("distributechart")
    public String distributechart(){return "charts/distributechart";}
    /**
     * 管理员登录认证
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> login(@RequestParam(value = "username") String username,
                                     @RequestParam(value = "password") String password,
                                     @RequestParam(value = "vcode") String vcode,
                                     @RequestParam(value = "usertype") String usertype,
                                     @RequestParam(value = "url_action") String url_action,
                                     HttpServletRequest request) {
        Map<String, String> ret = new HashMap<>();
        if (StringUtils.isEmpty(username)) {
            ret.put("type", "error");
            ret.put("msg", "用户名不能为空！");
            return ret;
        }
        if (StringUtils.isEmpty(password)) {
            ret.put("type", "error");
            ret.put("msg", "密码不能为空！");
            return ret;
        }
        if (StringUtils.isEmpty(vcode)) {
            ret.put("type", "error");
            ret.put("msg", "验证码不能为空！");
            return ret;
        }
        String loginCpacha = (String) request.getSession().getAttribute("loginCpacha");
        if (StringUtils.isEmpty(loginCpacha)) {
            ret.put("type", "error");
            ret.put("msg", "长时间未操作，会话已失效，请刷新后重试！");
            return ret;
        }
        /**   验证码校验 暂时关闭 系统上线后开启
         if(!vcode.equalsIgnoreCase(loginCpacha)){
         ret.put("type", "error");
         ret.put("msg", "验证码错误！");
         return ret;
         }*/


        /**
         * 管理员登录:
         **/
        if (usertype.equals("管理员")) {
            // 从t_admin数据库查询  用户
            AdminUser adminUser = adminLoginService.getAdminByName(username);
            if (adminUser == null) {
                ret.put("type", "error");
                ret.put("msg", "用户名错误！");
                return ret;
            }
            if (!password.equals(adminUser.getAdminPassword())) {
                ret.put("type", "error");
                ret.put("msg", "密码错误！");
                return ret;
            }
            //将用户信息存入session
            request.getSession().setAttribute("adminUser", adminUser);   //adminUser用户的power 控制前台某些菜单的显示
            request.getSession().setAttribute("onlineUserTrueName",adminUser.getAdminTrueName());
            request.getSession().setAttribute("onlineUserPower",adminUser.getPower());

            // 从后台获得统计表记录
            List<Statistics> statistics = statisticsService.getAllStatistics();
            request.getSession().setAttribute("statistics", statistics);
            // 从后台获得学期记录
            List<Semester> semesters = semesterService.getAllSemester();
            request.getSession().setAttribute("semesters", semesters);
            // 从后台获得考试
            List<Exam> examList = examService.getAllExam();
            request.getSession().setAttribute("examList", examList);
            // 从后台获得年级记录
            List<Grade> grades = gradeService.getAllGrades();

            //年级主任登录 只显示改年级
            if(adminUser.getPower() == 3){
                grades.clear();
                Grade tGrade=gradeService.getGradeByGradeName(adminUser.getGradeName());
                if (tGrade==null) {
                    ret.put("type", "error");
                    ret.put("msg", "当前管理员账号无年级信息，登录失败 ，请联系管理员！");
                    ret.put("userindex", url_action);
                    return ret;
                } else {grades.add(tGrade);}
            }

            request.getSession().setAttribute("grades", grades);
            // 从后台获得考试记录,过滤掉重复的考试名称
            List<Exam> tExams = examService.getAllExam();
            List<ExamView> exams = new ArrayList<>();
            for (int i = 0; i < tExams.size(); i++) {
                String t = tExams.get(i).getExamName();
                boolean tag = true;
                for (int j = 0; j < exams.size(); j++) {
                    if (exams.get(j).getExamName().equals(t)) {
                        tag = false;
                        break;
                    }
                }
                if (tag) {
                    ExamView tE = new ExamView();
                    tE.setExamName(t);
                    exams.add(tE);
                }
            }
            request.getSession().setAttribute("exams", exams);
            // 从后台获得分类记录
            List<Category> categorys = categoryService.getAllCategory();
            request.getSession().setAttribute("categorys", categorys);

            //获取班级 1-30班
            List<Team> teamsList = teamService.getTeams();
            request.getSession().setAttribute("teamsList", teamsList);
            //获取所有课程
            List<Course> courses = courseService.getCourses();
            request.getSession().setAttribute("courses", courses);

            request.getSession().removeAttribute("loginCpacha");    //移除验证码
            request.getSession().setMaxInactiveInterval(1800);    //设置登录session时间
            ret.put("type", "success");
            ret.put("msg", "登录成功！");
            ret.put("userindex", url_action);      //在index.html页面的ajax请求里面进行跳转
            return ret;
        }
        /**
         * 学生登录:
         * **/
        if (usertype.equals("学生")) {
            Student student = studentService.getStudentByIdcard(username);  //判断学生登录    从t_student查询   学生的登录用户名是学生的学籍号
            if (student == null) {
                ret.put("type", "error");
                ret.put("msg", "用户名错误！");
                return ret;
            }
            if (!password.equals(student.getPassword())) {
                ret.put("type", "error");
                ret.put("msg", "密码错误！");
                return ret;
            }
            //将学生信息存入session
            request.getSession().setAttribute("studentonline", student);
            request.getSession().setAttribute("onlineUserTrueName",student.getStudentName());
            request.getSession().removeAttribute("loginCpacha");    //移除验证码
            request.getSession().setMaxInactiveInterval(1800);    //设置登录session时间
            ret.put("type", "success");
            ret.put("msg", "登录成功！");
            ret.put("userindex", url_action);      //在index.html页面的ajax请求里面进行跳转
            return ret;
        }
        /**
         * 教师登录
         **/
        if (usertype.equals("教师")) {
            Teacher teacher = teacherService.getTeacherByTeacherIdcard(username);//教师登录    从t_teacher查询   登录用户名是教师身份证号
            if (teacher == null) {
                ret.put("type", "error");
                ret.put("msg", "用户名错误！");
                return ret;
            }
            if (!password.equals(teacher.getPassword())) {
                ret.put("type", "error");
                ret.put("msg", "密码错误！");
                return ret;
            }
            //将用户信息存入session
            request.getSession().setAttribute("teacheronline", teacher);
            request.getSession().setAttribute("onlineUserTrueName",teacher.getTeacherName());
            request.getSession().setAttribute("onlineUserPower",teacher.getRoleName());

            request.getSession().removeAttribute("loginCpacha");            //移除验证码
            request.getSession().setMaxInactiveInterval(1800);                      //设置登录session时间
            // 获取教师的任教信息
            List<TeachInfo> teachInfoList = teachInfoService.getTeachInfoByTeacherIdCard(teacher.getTeacherIdCard());
            if (teachInfoList.size() <= 0) {
                ret.put("type", "error");
                ret.put("msg", "无该教师的任教信息");
                return ret;
            }
            // 有教师的任教信息：将教师的任教信息存入session
            request.getSession().setAttribute("teachInfoList", teachInfoList);

            // 定义该教师任教的年级记录
            List<Grade> grades = new ArrayList<>();
            // 定义该教师任教的学期记录
            List<Semester> semesters = new ArrayList<>();
            // 定义该教师任教的所有班级
            List<String> teams = new ArrayList<>();
            // 定义该教师任教的所有课程
            List<Course> courses = new ArrayList<>();
            // 定义该教师任教的学科的考试名称列表
            List<ExamView> exams = new ArrayList<>();
            // 定义该教师任教的学科的考试分类列表
            List<Category> categorys = new ArrayList<>();
            // 通过教师任教信息获得教师任教的(年级，学期，班级，学科，考试，分类)列表
            for (int i = 0; i < teachInfoList.size(); i++) {
                // 从任教信息中获取任教的年级信息（Grade对象）
                boolean tag = true;
                String tGradeNameI = teachInfoList.get(i).getGradeName();
                for (int j = 0; j < grades.size(); j++) {
                    String tGradeNameJ = grades.get(j).getGradeName();
                    if (tGradeNameJ.equals(tGradeNameI)) {
                        tag = false;
                        break;
                    }
                }
                if (tag) grades.add(gradeService.getGradeByGradeName(tGradeNameI));
                //  从任教信息中获取任教的学期信息（Semester对象）
                tag = true;
                String tSemestersNameI = teachInfoList.get(i).getSemesterName();
                for (int j = 0; j < semesters.size(); j++) {
                    String tSemestersNameJ = semesters.get(j).getSemesterName();
                    if (tSemestersNameJ.equals(tSemestersNameI)) {
                        tag = false;
                        break;
                    }
                }
                if (tag) semesters.add(semesterService.getSemesterByName(tSemestersNameI));
                // 从任教信息中获取任教的班级信息(String字符串)
                tag = true;
                String tTeamNameI = teachInfoList.get(i).getTeamName();
                for (int j = 0; j < teams.size(); j++) {
                    String tTeamNameJ = teams.get(j);
                    if (tTeamNameJ.equals(tTeamNameI)) {
                        tag = false;
                        break;
                    }
                }
                if (tag) teams.add(tTeamNameI);
                // 从任教信息中获取任教的学科信息（Course对象）
                tag = true;
                String tCourseEnNameI = teachInfoList.get(i).getCourseEnName();
                for (int j = 0; j < courses.size(); j++) {
                    String tCourseEnNameJ = courses.get(j).getCourseEnName();
                    if (tCourseEnNameJ.equals(tCourseEnNameI)) {
                        tag = false;
                        break;
                    }
                }
                if (tag) courses.add(courseService.getCourseByCourseEnName(tCourseEnNameI));
            }
            // 存入session
            request.getSession().setAttribute("grades", grades);
            request.getSession().setAttribute("semesters", semesters);
            request.getSession().setAttribute("teams", teams);
            request.getSession().setAttribute("courses", courses);

            // 获取该教师当前任教信息的学生考试成绩（即教学成绩）
            for (int i = 0; i < teachInfoList.size(); i++) {
                Map<String, Object> paraMap = new HashMap<>();
                String gradeDatatableName = gradeService.getGradeByGradeName(teachInfoList.get(i).getGradeName()).getGradeDatatableName();
                paraMap.put("gradeDatatableName", gradeDatatableName);
                paraMap.put("gradeName", teachInfoList.get(i).getGradeName());
                paraMap.put("semesterName", teachInfoList.get(i).getSemesterName());
                paraMap.put("teamName", teachInfoList.get(i).getTeamName());
                paraMap.put("courseEnName", teachInfoList.get(i).getCourseEnName());
                paraMap.put("examName", "");

                List<TeachScore> teachScores = scoreService.getTeachScores(paraMap);
                // 从该教师当前教学成绩中“筛出”考试信息和分类信息
                for (int j = 0; j < teachScores.size(); j++) {
                    boolean tag = true;
                    // 筛出考试信息
                    String tExamNameJ = teachScores.get(j).getExamName();
                    for (int k = 0; k < exams.size(); k++) {
                        String tExamNameK = exams.get(k).getExamName();
                        if (tExamNameK.equals(tExamNameJ)) {
                            tag = false;
                            break;
                        }
                    }
                    if (tag) {
                        ExamView tE = new ExamView();
                        tE.setExamName(tExamNameJ);
                        exams.add(tE);
                    }

                    // 筛出分类信息
                    tag = true;
                    String tCategoryNameJ = teachScores.get(j).getCategoryName();
                    for (int k = 0; k < categorys.size(); k++) {
                        String tCategoryNameK = categorys.get(k).getCategoryName();
                        if (tCategoryNameK.equals(tCategoryNameJ)) {
                            tag = false;
                            break;
                        }
                    }
                    if (tag) categorys.add(categoryService.getCategoryByName(tCategoryNameJ));
                }
            }
            request.getSession().setAttribute("exams", exams);
            request.getSession().setAttribute("categorys", categorys);


            ret.put("type", "success");
            ret.put("msg", "登录成功！");
            ret.put("userindex", url_action);                   //在index.html页面的ajax请求里面进行跳转
            return ret;
        }
        ret.put("type", "error");
        ret.put("msg", "登录失败 ，请联系管理员！");
        ret.put("userindex", url_action);
        return ret;

    }

    /**
     * 显示 验证码
     */
    @RequestMapping(value = "/get_cpacha", method = RequestMethod.GET)
    public void getCpacha(HttpServletRequest request,
                          @RequestParam(value = "vl", defaultValue = "4", required = false) Integer vl,
                          @RequestParam(value = "w", defaultValue = "98", required = false) Integer w,
                          @RequestParam(value = "h", defaultValue = "35", required = false) Integer h, HttpServletResponse response) {
        CpachaUtil cpachaUtil = new CpachaUtil(vl, w, h);
        String generatorVCode = cpachaUtil.generatorVCode();
        request.getSession().setAttribute("loginCpacha", generatorVCode);
        BufferedImage generatorRotateVCodeImage = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
        try {
            ImageIO.write(generatorRotateVCodeImage, "gif", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 注销登录
     */
    @RequestMapping(value = "/login_out", method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/index";
    }
}
